import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

// 假设存在ResulttDAO接口
public class ResultDAOImpl implements ResultDAO {
    // 实现接口中的findByAccount方法
    @Override
    public Result findByAccount(String account) {
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "SELECT * FROM Result WHERE account =?";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, account);
            ResultSet resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                Result result = new Result();
                result.setAccount(resultSet.getString("account"));
                result.setMbti(resultSet.getString("mbti"));
                return result;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 实现接口中的getAllResults方法
    @Override
    public List<Result> getAllResults() {
        List<Result> results = new ArrayList<>();
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "SELECT * FROM Result";
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                Result result = new Result();
                result.setAccount(resultSet.getString("account"));
                result.setMbti(resultSet.getString("mbti"));
                results.add(result);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return results;
    }

    // 实现接口中的save方法
    @Override
    public void save(Result result) {
        if (result == null || result.getAccount() == null) {
            System.err.println("无法保存结果，账号为空");
            return;
        }
        try (Connection connection = DBUtil.getConnection()) {
            // 先检查是否已经存在相同记录
            String checkSql = "SELECT * FROM Result WHERE account =? AND mbti =?";
            PreparedStatement checkStatement = connection.prepareStatement(checkSql);
            checkStatement.setString(1, result.getAccount());
            checkStatement.setString(2, result.getMbti());
            ResultSet resultSet = checkStatement.executeQuery();
            if (!resultSet.next()) {
                // 如果不存在相同记录，再进行插入操作
                String sql = "INSERT INTO Result (account, mbti) VALUES (?,?)";
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, result.getAccount());
                preparedStatement.setString(2, result.getMbti());
                preparedStatement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}